package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.pojo.*;
import com.zhentao.service.*;
import com.zhentao.vo.QueryParam;
import com.zhentao.vo.Result;
import org.apache.commons.lang.time.DateUtils;
import org.omg.PortableServer.POA;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/doctors")
public class DoctorController {
    @Autowired
    private DoctorService service;
    @Autowired
    private DoctorScheduleService doctorScheduleService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private SourceService sourceService;
    @Autowired
    private DoctorService doctorService;

    @RequestMapping("findDoc")
    public Result findDoc(@RequestBody QueryParam queryParam){
        Page<Doctor> page = service.findPage(queryParam);
        return Result.OK(page);
    }

    @RequestMapping("findDcoById")
    public Doctor findDocById(Integer id){
        Doctor doctor = service.getById(id);
        Integer rid = doctor.getRid();
        Role role = roleService.getById(rid);
        doctor.setRole(role);
        Integer departmentid = doctor.getDepartmentid();
        Department department = departmentService.getById(departmentid);
        doctor.setDepartment(department);
        return doctor;
    }

    @RequestMapping("findDocByIdScheduleAndSource")
    public Result findDocById(@RequestBody QueryParam queryParam){
        Page<DoctorSchedule> page = doctorScheduleService.findPage(queryParam);
        return Result.OK(page);
    }

    @RequestMapping("updateScheduleAndSources")
    public Result updateScheduleAndSources(@RequestBody ScheduleUpdateDTO scheduleUpdateDTO){
        return doctorScheduleService.updateScheduleWithSources(scheduleUpdateDTO);
    }

    // 新增获取排班详情接口
    @RequestMapping("getScheduleDetail/{id}")
    public Result getScheduleDetail(@PathVariable Integer id) {
        DoctorSchedule schedule = doctorScheduleService.getById(id);
        schedule.setSources(sourceService.lambdaQuery()
                .eq(Source::getScheduleId, id)
                .list());
        return Result.OK(schedule);
    }

    @RequestMapping("delScheduleAndSources")
    public Result delScheduleAndSources(Integer id){
        DoctorSchedule schedule = doctorScheduleService.getById(id);
        Integer scheduleId = schedule.getScheduleId();
        doctorScheduleService.removeById(schedule);
        List<Source> sources = sourceService.selectByScheduleId(scheduleId);
        sourceService.removeByIds(sources);
        return Result.OK();
    }

    @RequestMapping("luojiDel")
    public Result luojiDel(Integer id){
        boolean bool = service.removeById(id);
        if (bool){
            return Result.OK("删除成功");
        }else {
            return Result.ERROR("删除失败");
        }
    }

    @RequestMapping("/addSchedule")
    public Result addDoc(@RequestBody ScheduleDTO dto) {
        // 基础校验
        if (dto.getDate() == null || dto.getTimeSlots().isEmpty()) {
            return Result.ERROR("参数不完整");
        }

        // 日期校验
        Date now = new Date();
        if (dto.getDate().before(DateUtils.truncate(now, Calendar.DATE))) {
            return Result.ERROR("不能选择过去日期");
        }

        // 当天时段校验
        if (DateUtils.isSameDay(dto.getDate(), now)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

            for (String timeSlot : dto.getTimeSlots()) {
                try {
                    String[] parts = timeSlot.split("-");
                    Date startTime = sdf.parse(
                            new SimpleDateFormat("yyyy-MM-dd").format(dto.getDate())
                                    + " " + parts[0]
                    );

                    if (startTime.before(now)) {
                        return Result.ERROR("包含已过期时段：" + timeSlot);
                    }
                } catch (ParseException e) {
                    return Result.ERROR("时间格式错误：" + timeSlot);
                }
            }
        }


        // 2. 检查是否已存在相同日期的排班
        LambdaQueryWrapper<DoctorSchedule> query = new LambdaQueryWrapper<>();
        query.eq(DoctorSchedule::getDoctorId, dto.getDoctorId())
                .apply("DATE(date) = STR_TO_DATE({0}, '%Y-%m-%d')", dto.getDate()); // 修改这里

        if (doctorScheduleService.count(query) > 0) {
            return Result.ERROR("该医生当天已有排班");
        }

        // 3. 保存排班信息（原有逻辑）
        DoctorSchedule doctorSchedule = new DoctorSchedule();
        doctorSchedule.setDoctorId(dto.getDoctorId());
        doctorSchedule.setStatus("normal");
        doctorSchedule.setMaxPatients(30);
        doctorSchedule.setDate(dto.getDate());
        doctorScheduleService.save(doctorSchedule);

        // 4. 保存号源信息（优化批量插入）
        List<Source> sources = dto.getTimeSlots().stream().map(timeSlot -> {
            Source source = new Source();
            source.setScheduleId(doctorSchedule.getScheduleId());
            source.setFee(BigDecimal.valueOf(15.00));
            source.setRemaining(30);
            source.setTotal(30);
            source.setTimeSlot(timeSlot);
            return source;
        }).collect(Collectors.toList());

        sourceService.saveBatch(sources);

        return Result.OK();
    }

    @RequestMapping("addDoc")
    public Result addDoc(@RequestBody Doctor doctor){
        doctor.setDeleted(0);
        System.err.println(doctor.getDepartmentid());
        boolean save = service.save(doctor);
        if (save){
            return Result.OK();
        }else {
            return Result.ERROR();
        }
    }

    @RequestMapping("upload")
    public Result upload(MultipartFile file){
        try {
        String originalFilename = file.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        String substring = originalFilename.substring(index);
        String newName = UUID.randomUUID().toString().replaceAll("-", "");
        String path = "D:\\idewenjiain\\img";
        File file1 = new File(path, newName);
        file.transferTo(file1);
        String url = "http://localhost:8081/img/"+newName;
        return Result.OK(url);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.ERROR("上传失败");
        }
    }

    @RequestMapping("updateDoctor")
    public Result updateByDcotorId(@RequestBody Doctor doctor){
        service.updateById(doctor);
        return Result.OK();
    }


    @RequestMapping("findPatient")
    public Result findPatient(Integer doctorId){
        List<Patient> patient = doctorService.findPatient(doctorId);
        return Result.OK(patient);
    }





}
